//
//  GroupInfoViewController.m
//  sentorise
//
//  Created by admin on 2025/9/16.
//

#import "GroupInfoViewController.h"
#import "GlobalDefine.h"
#import "ProgressHUD.h"
#import "GroupSPCollectionViewCell.h"
#import "BTManager.h"
#import "GroupItemInfoView.h"
#import "DeviceDataInfoViewController.h"
#import "GroupItemInfoErrorView.h"
#import "GroupSetSPViewController.h"

@implementation BluetoothParaInfo

@end

@implementation ExtremeValues

@end

@interface GroupInfoViewController ()

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topS;

@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *typeLabel;

@property (weak, nonatomic) IBOutlet UILabel *powerLabel;
@property (weak, nonatomic) IBOutlet UILabel *currentLabel;
@property (weak, nonatomic) IBOutlet UILabel *voltageLabel;
@property (weak, nonatomic) IBOutlet UILabel *capacityLabel;

@property (weak, nonatomic) IBOutlet UILabel *spLabel;

@property (weak, nonatomic) IBOutlet UICollectionView *spCollect;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *spCollectH;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *spCollectW;

@property (weak, nonatomic) IBOutlet UILabel *overviewLabel;
@property (weak, nonatomic) IBOutlet UILabel *powerTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *currentTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *voltageTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *capTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *configTitleLabel;
@property (weak, nonatomic) IBOutlet UIButton *refrshBtn;

@property (nonatomic, strong) NSMutableArray<BlutoothModel *> *dataArray;
@property (nonatomic, strong) NSMutableArray<NSDictionary *> *batteryLevelSource;

@property (nonatomic, assign) NSInteger colums;
@property (nonatomic, assign) NSInteger rows;
@property (nonatomic, assign) CGFloat collectItemW;

@end

@implementation GroupInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.topS.constant = IPHONE_X ? 54 : 20;
    self.overviewLabel.text = NSLocalizedString(@"Overview", nil);
    self.powerTitleLabel.text = NSLocalizedString(@"System Power", nil);
    self.currentTitleLabel.text = NSLocalizedString(@"System Current", nil);
    self.voltageTitleLabel.text = NSLocalizedString(@"System voltage", nil);
    self.capTitleLabel.text = NSLocalizedString(@"Remaining Capacity", nil);
    self.configTitleLabel.text = NSLocalizedString(@"System Configuration", nil);
    [self.refrshBtn setTitle:NSLocalizedString(@"Refresh", nil) forState:UIControlStateNormal];
    
    self.dataArray = [[NSMutableArray alloc] init];
    self.colums = self.model.s.integerValue;
    self.rows = self.model.p.integerValue;
    [self.dataArray addObjectsFromArray:self.model.bluList];
    self.batteryLevelSource = [[NSMutableArray alloc] init];

    self.nameLabel.text = self.model.groupName;
    self.spLabel.text = [NSString stringWithFormat:@"%@P%@S", self.model.p, self.model.s];
    self.collectItemW = (kWidth - 40) / 2;
    if (self.colums == 1) {
        self.collectItemW = (kWidth - 40);
    }else if(self.colums > 2) {
        self.collectItemW -= 20;
    }
    self.spCollectW.constant = self.collectItemW * self.colums;
    self.spCollectH.constant = 96 * self.rows;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadBatteryLevel:) name:kBTGetBatteryLevel object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadData) name:kBTBluGroupChanged object:nil];

    [self.spCollect registerNib:[UINib nibWithNibName:@"GroupSPCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"GroupSPCollectionViewCell"];
    
    [self startQuery];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([BTManager sharedBTManager].lookSocBlues.count && ![BTManager sharedBTManager].isGettingBattery) {
        [BTManager sharedBTManager].isGettingBattery = YES;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [BTManager sharedBTManager].isGettingBattery = NO;
}

- (void)startQuery {
    [BTManager sharedBTManager].lookSocBlues = @[];
    [BTManager sharedBTManager].isGettingBattery = NO;
    NSMutableArray *bles = [NSMutableArray array];
    for (CBPeripheral *p in [BTManager sharedBTManager].peripherals) {
        for (BlutoothModel *model in self.model.bluList) {
            if ([p.identifier.UUIDString isEqualToString:model.uuid]) {
                [bles addObject:p];
                break;
            }
        }
    }
    [BTManager sharedBTManager].lookSocBlues = bles;
    [BTManager sharedBTManager].isGettingBattery = YES;
}

- (void)reloadData {
    [BTManager sharedBTManager].lookSocBlues = @[];
    NSString *groupStr = [[NSUserDefaults standardUserDefaults] objectForKey:BatteryGroupBluList] ?: @"";
    if (groupStr.length) {
        NSArray *dataArray = [BlutoothGroupModel jsonCovertToModel:groupStr];
        for (BlutoothGroupModel *model in dataArray) {
            if (model.groupId == self.model.groupId) {
                self.model = model;
                break;
            }
        }
    }
    [self actionRefresh:[UIButton new]];
    [self.dataArray removeAllObjects];
    [self.dataArray addObjectsFromArray:self.model.bluList];
    [self.spCollect reloadData];
    if (![BTManager sharedBTManager].isGettingBattery) {
        [self startQuery];
    }
}

- (void)reloadBatteryLevel:(NSNotification *)nf {
    NSArray *list = nf.object;
    [self.batteryLevelSource removeAllObjects];
    [self.batteryLevelSource addObjectsFromArray:list];
    [self.spCollect reloadData];

    NSMutableArray *arr = [NSMutableArray array];
    for (NSInteger i=0; i<self.dataArray.count; i++) {
        NSString *name = self.dataArray[i].name;
        BluetoothParaInfo *info = [[BluetoothParaInfo alloc] init];
        for (NSDictionary *dict in self.batteryLevelSource) {
            if ([name isEqualToString:[dict objectForKey:@"name"]]) {
                info.currentVoltage = [[dict objectForKey:@"voltage"] floatValue];
                info.currentCharging = [[dict objectForKey:@"chargeC"] floatValue];
                info.currentDischarge = [[dict objectForKey:@"dischargeC"] floatValue];
                info.currentCapacity = [[dict objectForKey:@"capcity"] floatValue];
                info.maxTemperature = [[dict objectForKey:@"maxTemp"] floatValue];
                info.currentSoc = [[dict objectForKey:@"soc"] floatValue];
                break;
            }
        }
        [arr addObject:info];
    }
    
    ExtremeValues *values = [self calculateBatteryMatrixWithDataList:arr series:self.colums parallel:self.rows];
    self.voltageLabel.text = [NSString stringWithFormat:@"%.1fV", values.totalVoltage];
    self.currentLabel.text = [NSString stringWithFormat:@"%@%.1fA", values.totalDischargeCurrent > 0 ? @"-" : values.totalChargeCurrent > 0 ? @"+" : @"", values.totalDischargeCurrent > 0 ? values.totalDischargeCurrent :  values.totalChargeCurrent];
    self.capacityLabel.text = [NSString stringWithFormat:@"%.1fAh", values.totalRemainingCapacity];
    self.powerLabel.text = [NSString stringWithFormat:@"%.1fW", values.totalPower];
}

- (IBAction)actionBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)actionRefresh:(id)sender {
    [self.batteryLevelSource removeAllObjects];
    self.voltageLabel.text = @"0V";
    self.currentLabel.text = @"0A";
    self.capacityLabel.text = @"0Ah";
    self.powerLabel.text = @"0W";
    [self.spCollect reloadData];
    [[BTManager sharedBTManager].batteryLevelSource removeAllObjects];
    
//    if (![BTManager sharedBTManager].isGettingBattery) {
//        [self startQuery];
//    }
    [BTManager sharedBTManager].lookSocBlues = @[];
    [BTManager sharedBTManager].isGettingBattery = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (![BTManager sharedBTManager].isGettingBattery) {
            [self startQuery];
        }
    });
}

- (IBAction)actionSet:(id)sender {
    GroupSetSPViewController *vc = [[GroupSetSPViewController alloc] initWithNibName:@"GroupSetSPViewController" bundle:nil];
    vc.model = self.model;
    vc.isQueryIn = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GroupSPCollectionViewCell *cell = (GroupSPCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"GroupSPCollectionViewCell" forIndexPath:indexPath];
    BOOL isFirstLine = indexPath.item < self.colums;
    BOOL isLastLine = indexPath.item >= self.colums * (self.rows - 1);
    if (self.rows == 1) {
        cell.lhView.hidden = indexPath.item == 0;
        cell.rhView.hidden = indexPath.item == self.dataArray.count - 1;
    }
    cell.ltView.hidden = isFirstLine;
    cell.rtView.hidden = isFirstLine;
    cell.lbView.hidden = isLastLine;
    cell.rbView.hidden = isLastLine;
    BlutoothModel *blu = self.dataArray[indexPath.item];
    cell.delBtn.hidden = YES;
    cell.addIV.hidden = YES;
    cell.batterIV.hidden = NO;
    cell.nameLabel.hidden = NO;
    cell.nameLabel.text = blu.name;
    if (!self.batteryLevelSource.count) {
        cell.warnIV.hidden = YES;
        cell.normalView.hidden = YES;
        cell.bgView.backgroundColor = [UIColor whiteColor];
    }else {
        NSString *warn = @"-1";
        for (NSDictionary *dict in self.batteryLevelSource) {
            if ([[dict objectForKey:@"name"] isEqualToString:self.dataArray[indexPath.item].name]) {
                warn = [NSString stringWithFormat:@"%@", [dict objectForKey:@"warn"] ?: @"0"];
                break;
            }
        }
        if ([warn isEqualToString:@"-1"]) {
            cell.warnIV.hidden = YES;
            cell.normalView.hidden = YES;
            cell.bgView.backgroundColor = [UIColor whiteColor];
        }else if ([warn isEqualToString:@"0"]) {
            cell.warnIV.hidden = YES;
            cell.normalView.hidden = NO;
            cell.bgView.backgroundColor = [UIColor whiteColor];
        }else {
            cell.warnIV.hidden = NO;
            cell.normalView.hidden = YES;
            cell.bgView.backgroundColor = RGB16(0xFFD4D4);
        }
    }
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(self.collectItemW, 96);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    BlutoothModel *blu = self.dataArray[indexPath.item];
    NSString *current = @"0";
    NSString *voltage = @"0";
    NSString *capacity = @"0";
    NSString *warn = @"0";
    for (NSDictionary *dict in self.batteryLevelSource) {
        if ([[dict objectForKey:@"name"] isEqualToString:blu.name]) {
            warn = [NSString stringWithFormat:@"%@", [dict objectForKey:@"warn"] ?: @"0"];
            capacity = [NSString stringWithFormat:@"%@", [dict objectForKey:@"capcity"] ?: @"0"];
            voltage = [NSString stringWithFormat:@"%@", [dict objectForKey:@"voltage"] ?: @"0"];
            CGFloat dischargeC = [([dict objectForKey:@"dischargeC"] ?: @"0") floatValue];
            current = [NSString stringWithFormat:@"%@", dischargeC > 0 ? ([dict objectForKey:@"dischargeC"] ?: @"0") : ([dict objectForKey:@"chargeC"] ?: @"0")];
            break;
        }
    }
    if ([warn integerValue]) {
        GroupItemInfoErrorView *view = (GroupItemInfoErrorView *)[[[NSBundle mainBundle] loadNibNamed:@"GroupItemInfoErrorView" owner:self options:nil] firstObject];
        view.nameLabel.text = blu.name;
        view.frame = [[UIScreen mainScreen] bounds];
        [[UIApplication sharedApplication].delegate.window addSubview:view];
        WeakSelf
        view.clickItem = ^(NSInteger index) {
            if (index == 0) {
                DeviceDataInfoViewController *vc = [[DeviceDataInfoViewController alloc] initWithNibName:@"DeviceDataInfoViewController" bundle:nil];
                vc.model = blu;
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }
        };
        return;
    }
    GroupItemInfoView *view = (GroupItemInfoView *)[[[NSBundle mainBundle] loadNibNamed:@"GroupItemInfoView" owner:self options:nil] firstObject];
    view.frame = [[UIScreen mainScreen] bounds];
    [[UIApplication sharedApplication].delegate.window addSubview:view];
    view.nameLabel.text = blu.name;
    view.powerLabel.text = [NSString stringWithFormat:@"%.2fW", [current floatValue] * [voltage floatValue]];
    view.currentLabel.text = [NSString stringWithFormat:@"%.1fA", [current floatValue]];
    view.voltageLabel.text = [NSString stringWithFormat:@"%.1fV", [voltage floatValue]];
    view.socLabel.text = [NSString stringWithFormat:@"%.1fAh", [capacity floatValue]];
    WeakSelf
    view.clickItem = ^(NSInteger index) {
        if (index == 0) {
            DeviceDataInfoViewController *vc = [[DeviceDataInfoViewController alloc] initWithNibName:@"DeviceDataInfoViewController" bundle:nil];
            vc.model = blu;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    };
}

- (ExtremeValues *)calculateBatteryMatrixWithDataList:(NSArray<BluetoothParaInfo *> *)dataList series:(NSInteger)series parallel:(NSInteger)parallel {
    NSAssert(series > 0, @"每行电池数(series)必须大于0");
    NSAssert(parallel > 0, @"总行数(parallel)必须大于0");

    NSInteger validDataCount = 0;
    float totalTemperature = 0.0f;
    float totalSoc = 0.0f;

    float totalVoltage = 0.0f;
    float totalChargeCurrent = 0.0f;
    float totalDischargeCurrent = 0.0f;
    float totalRemainingCapacity = 0.0f;
    float totalPower = 0.0f;

    NSInteger actualParallelCount = 0;
    float firstValidRowVoltage = 0.0f;

    if (dataList.count < series * parallel) {
        NSLog(@"警告: 数据量不足(需要%ld个，实际%lu个)", (long)(series * parallel), (unsigned long)dataList.count);
    }

    for (NSInteger rowIndex = 0; rowIndex < parallel; rowIndex++) {
        NSInteger startIdx = rowIndex * series;
        NSInteger endIdx = MIN((rowIndex + 1) * series, dataList.count);
        NSArray *rowData = [dataList subarrayWithRange:NSMakeRange(startIdx, endIdx - startIdx)];

        float rowVoltageSum = 0.0f;
        float rowChargingSum = 0.0f;
        float rowDischargeSum = 0.0f;
        float rowCapacitySum = 0.0f;
        NSInteger rowValidCount = 0;

        for (BluetoothParaInfo *cell in rowData) {
            float voltage = cell.currentVoltage;
            if (voltage == 0.0f) continue;

            rowVoltageSum += voltage;
            rowChargingSum += cell.currentCharging;
            rowDischargeSum += cell.currentDischarge;
            rowCapacitySum += cell.currentCapacity;

            totalTemperature += cell.maxTemperature;
            totalSoc += cell.currentSoc;

            rowValidCount++;
            validDataCount++;
        }

        if (rowValidCount > 0) {
            if (actualParallelCount == 0) {
                firstValidRowVoltage = rowVoltageSum;
            } else if (fabsf(rowVoltageSum - firstValidRowVoltage) > 0.1f) {
                NSLog(@"警告: 行%ld电压不一致 (%.2fV vs 基准%.2fV)", (long)(rowIndex + 1), rowVoltageSum, firstValidRowVoltage);
            }

            float rowChargingAvg = rowChargingSum / rowValidCount;
            float rowDischargeAvg = rowDischargeSum / rowValidCount;
            float rowCapacityAvg = rowCapacitySum / rowValidCount;
            float rowCurrent = rowChargingAvg - rowDischargeAvg;
            float rowPower = rowVoltageSum * rowCurrent;

            totalChargeCurrent += rowChargingAvg;
            totalDischargeCurrent += rowDischargeAvg;
            totalRemainingCapacity += rowCapacityAvg;
            totalPower += rowPower;

            actualParallelCount++;
        }
    }

    totalVoltage = actualParallelCount > 0 ? firstValidRowVoltage : 0.0f;
    float avgTemp = validDataCount > 0 ? totalTemperature / validDataCount : 0.0f;
    float avgSoc = validDataCount > 0 ? totalSoc / validDataCount : 0.0f;

    ExtremeValues *result = [[ExtremeValues alloc] init];
    result.averageTemperature = avgTemp;
    result.averageSoc = (int)(roundf(avgSoc));
    result.totalVoltage = totalVoltage;
    result.totalChargeCurrent = totalChargeCurrent;
    result.totalDischargeCurrent = totalDischargeCurrent;
    result.totalRemainingCapacity = totalRemainingCapacity;
    result.totalPower = totalPower;

    return result;
}


@end
